package com.k12.admim.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultLitePullConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class RocketMQPullConsumer{
    @Resource
    private DefaultLitePullConsumer defaultLitePullConsumer;

    @PreDestroy
    public void destroy() {
        defaultLitePullConsumer.shutdown();
    }

    /**
     * 定时拉取消息（推荐使用Scheduled控制拉取频率）
     */
    @Scheduled(fixedDelay = 100) // 根据业务调整频率
    public void pollMessages() {
        List<MessageExt> messages = defaultLitePullConsumer.poll();
        if (messages.isEmpty()) {
            log.info("No new messages.......");
            return;
        }
        for (MessageExt message : messages) {
            try {
                // 业务处理
               message.getMsgId() ;
               message.getBody() ;
               log.info("Processing message, msgId: {}", message.getMsgId());
               log.info("Processing message, msgBody: {}", message.getMsgId());
                // 提交消费位点（自动模式可省略）
                defaultLitePullConsumer.commitSync();
            }  catch (Exception e) {
                log.error("Process failed, msgId: {}", message.getMsgId(), e);
                // 超过重试次数进入死信队列
            }
        }
    }

}